<?php

namespace App\Http\Controllers\admin;

use App\AmountModel;
use App\ArticleModel;
use App\Http\Controllers\Controller;
use App\TypeModel;
use App\UserModel;
use App\VipModel;
use Illuminate\Http\Request;

class AmountController extends Controller
{
    public function amountorder(Request $request)
    {
        $openid = $request->input("openid");
        $grade = $request->input("grade");
        if ($grade == 1) {
            $amount = 500;

        } elseif ($grade == 2) {
            $amount = 1000;

        } elseif ($grade == 3) {
            $amount = 3000;
        }

        if ($grade == 4) {
            $amount = 5000;

        } elseif ($grade == 5) {
            $amount = 8000;

        } elseif ($grade == 6) {
            $amount = 10000;
        }
        $amountorder = AmountModel::create([
            'openid' => $openid,
            'grade' => $grade,
            'amount' => $amount,
        ]);

        $amountNotifyURL = ROOT_URL . "/api/amountnotify";
        $payment = new PayController();
        $final = $payment->createunifyorder($amountorder->openid, "充值余额", $amountorder->id, $amountorder->amount, $amountNotifyURL);
        return $this->success($final);
    }


    public function amountnotify(Request $request)
    {
        $data = file_get_contents("php://input");
//        file_put_contents("amountnotify" . rand(9, 99) . ".txt", $data);
        $data = $this->xmlToArray($data);
        $amountorder = AmountModel::find($data['attach']);
        $amountorder->state = 1;
        $amountorder->save();
        $user = UserModel::where('openid', $amountorder->openid)->first();
        $user->amount =  $amountorder->amount;
        $user->save();
        $result = [
            "return_code" => "SUCCESS",
            "return_msg" => "SUCCESS",
        ];
        return $this->arrayToXml($result);
    }


    //数组转换成xml
    private function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $xml .= "<" . $key . ">" . $this->arrayToXml($val) . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    //xml转换成数组
    private function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring), true);
        return $val;
    }
}
